package com.shinetech.controller;

import com.shinetech.entity.BaseEntity;
import com.shinetech.service.BaseService;
import com.shinetech.vo.ObjectRestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by joy on 2017/6/30.
 */

public abstract class BaseController<Entity extends BaseEntity>{
    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected BaseService<Entity> service;

    protected String getCurrentUserName(){
//        String authorization = request.getHeader("Authorization");
//        return new String(Base64Utils.decodeFromString(authorization));
        return "admin";
    }

    @PostMapping("")
    public ObjectRestResponse<Entity> save(Entity entity){
        service.save(entity);
        return new ObjectRestResponse<Entity>().rel(true);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ObjectRestResponse<Entity> get(@PathVariable int id){
        ObjectRestResponse response = new ObjectRestResponse<Entity>().rel(true).result(service.getOne(id));
        return response;
    }

    @PutMapping(value = "/{id}")
    public ObjectRestResponse<Entity> update(Entity entity){
        service.updateById(entity);
        return new ObjectRestResponse<Entity>().rel(true);
    }

    @DeleteMapping(value = "/{ids}")
    public ObjectRestResponse<Entity> remove(@PathVariable List<Long> ids){
        service.deleteByIds(ids);
        return new ObjectRestResponse<Entity>().rel(true);
    }

    @GetMapping(value = "/all")
    public List<Entity> list(){
        return service.selectListAll();
    }

}
